const Ws = require('ws')

;((Ws) => {
  // ws:localhost:8000
  const server = new Ws.Server({
    port: 8000
  })
  const init = () => {
    bindEvents()
  }
  
  const bindEvents = () => {
    server.on('open', handleOpen)
    // message 不是通过server来绑定的
    // server.on('message', handleMessage)
    server.on('close', handleClose)
    server.on('error', handleError)
    server.on('connection', handleConnection)
  }
  
  const handleOpen = () => {
    console.log('socked-open')
  }
  
  const handleConnection = (ws) => {
    // ws.send('hello')
    ws.on('message', handleMessage)
    // 执行 说明连接成功
    console.log('socked-connection')
  }
  
  const handleMessage = (msg) => {
    const buf = Buffer.from(msg, 'utf-8')
    console.log('socked-message:服务器接收到的数据', buf.toString('utf-8'));
    // console.log('socked-message:服务器接收到的数据',Buffer.from(msg,'utf-8'))
    
    // server.clients.forEach((client) => {
    //   if (client.readyState === Ws.OPEN) {
    //     client.send(buf.toString('utf-8'))
    //   }
    // })
    // 向前端发送消息
    server.clients.forEach(function (client) {
      client.send(buf.toString('utf-8'))
    })
  }
  
  
  const handleClose = () => {
    console.log('socked-close')
  }
  
  const handleError = () => {
    console.log('socked-error')
  }
  init()
  
  
})(Ws)
